﻿// ----------------------------------------------------------------------------
//  Copyright (C) 成都联宇创新科技有限公司 版权所有。 
//      
//  文件名：Bootstrap.cs
//  文件功能描述：
//  创建标识：骆智慧 2016/03/02 02:46
//     
//  修改标识：骆智慧  2016/03/10/06:40
//  修改描述：
//  ----------------------------------------------------------------------------

#region 导入名称空间

using System;
using Autofac;
using Autofac.Configuration;
using LightWork.Autofac.CommonServiceLocator;
using LightWork.DynamicProxy;
using LightWork.Interceptor;
using LightWork.ServiceLocation;
using LightWork.Services;
using LightWork.Topshelf.Autofac;
using LightWork.Topshelf.Common.Logging;
using Topshelf;

#endregion

namespace LightWork
{
    /// <summary>
    /// 引导程序
    /// </summary>
    public static class Bootstrap
    {
        private static bool _isInit;

        static Bootstrap()
        {
            Initiate();
        }

        public static IServiceLocator SeviceLocator { get; set; }

        public static IContainer AutofacContainer { get; set; }

        /// <summary>
        /// 生成动态代理 (使用 LightWork.Interceptor.LightWorkInterceptor)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        public static T CreateProxy<T>(T target) where T : class
        {
            return CreateProxy(target, new LogInterceptor());
        }

        /// <summary>
        /// 生成动态代理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <param name="interceptorImpl">拦截器实现</param>
        /// <returns></returns>
        public static T CreateProxy<T>(T target, IInterceptor interceptorImpl) where T : class
        {
            var _dyProxyGenerator = new ProxyGenerator(new PersistentProxyBuilder());
            return _dyProxyGenerator.CreateInterfaceProxyWithTarget(target, interceptorImpl);
        }

        /// <summary>
        /// 初始化集成框架
        /// </summary>
        [STAThread]
        public static void Initiate()
        {
            if (_isInit) return;

            var builder = new ContainerBuilder();
            builder.RegisterType<LogInterceptor>()
                .As<IInterceptor>()
                .AsSelf();

            builder.RegisterModule<LightWorkModule>();
            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            AutofacContainer = builder.Build();
            SeviceLocator = new AutofacServiceLocator(AutofacContainer);
            _isInit = true;
        }


        /// <summary>
        /// 启动 Windows 服务宿主
        /// </summary>
        [STAThread]
        public static TopshelfExitCode RunWindowHost()
        {
            Initiate();
            var exitCode = HostFactory.Run(hostCfg =>
            {
                #region 基础配置

                hostCfg.UseCommonLogging();
                hostCfg.UseAutofacContainer(AutofacContainer);
                hostCfg.UseCustomerConfigure();
                hostCfg.SetStartTimeout(new TimeSpan(0, 0, 0, 3));

                #endregion

                #region 高级选项设置

                hostCfg.EnableShutdown();
                hostCfg.EnableServiceRecovery(recovery =>
                {
                    recovery.RestartService(2);
                    recovery.RestartService(3);
                    recovery.RestartService(5);
                    recovery.SetResetPeriod(1); //重置计数器频率
                });

                #endregion

                #region 设置运行信息并启动

                hostCfg.Service<QuartzService>(serviceConfigurator =>
                {
                    serviceConfigurator.ConstructUsingAutofacContainer();
                    serviceConfigurator.WhenStarted((service, host) => service.Start());
                    serviceConfigurator.WhenPaused((service, host) => service.Pause());
                    serviceConfigurator.WhenContinued((service, host) => service.Continue());
                    serviceConfigurator.WhenStopped((service, host) =>
                    {
                        try
                        {
                            AutofacHostBuilderConfigurator.LifetimeScope.Dispose();
                            AutofacContainer.Dispose();
                            return service.Stop();
                        }
                        catch
                        {
                            return false;
                        }
                    });
                });

                #endregion
            });

            return exitCode;
        }
    }
}